package com.download.net;

import java.io.File;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;

import com.download.cache.MemoryCache;

import android.graphics.Bitmap;
import android.widget.ImageView;

public class ImageLoader implements DCallback {
	private Downloader dloader = Downloader.getInstance();
	private MemoryCache memoryCache = new MemoryCache();
	private Map<ImageView, String> imageViews = 
			Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
	
	public boolean DisplayImage(String url, ImageView imageView, Boolean isLoadOnlyFromCache){
		if (isLoadOnlyFromCache) {
			Bitmap bm = memoryCache.get(url);
			if (bm == null) {
				// 刷新界面
			}
			else {
				return false;
			}
		}
		
		// 根据参数再尝试本地和网络异步取获取文件
		DTask task = new DTask(url, this);
		dloader.downloadFile(task, true, true);
		return true;
	}

	@Override
	public void finish(DTask task, Boolean bSuccess, File file) {
		// TODO Auto-generated method stub
		
	}
	
	// Task for the queue
	private class PhotoToLoad {
		public String url;
		public ImageView imageView;

		public PhotoToLoad(String u, ImageView i) {
			url = u;
			imageView = i;
		}
	}
	
	boolean imageViewReused(PhotoToLoad photoToLoad) {
		String tag = imageViews.get(photoToLoad.imageView);
		if (tag == null || !tag.equals(photoToLoad.url))
			return true;
		return false;
	}

	// ������UI�߳��и��½���
	class BitmapDisplayer implements Runnable {
		Bitmap bitmap;
		PhotoToLoad photoToLoad;

		public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
			bitmap = b;
			photoToLoad = p;
		}

		public void run() {
			if (imageViewReused(photoToLoad))
				return;
			if (bitmap != null)
				photoToLoad.imageView.setImageBitmap(bitmap);
	
		}
	}

	public void clearCache() {
		memoryCache.clear();
		fileCache.clear();
	}

}
